const path = require('path');
const webpack = require('webpack');
const isDev = process.env.NODE_ENV === 'development'
const config = require('./public/config')[isDev ? 'dev' : 'build']
const apiMocker = require('mocker-api');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssPlugin = require('optimize-css-assets-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const SpeedMeasureWebpackPlugin = require('speed-measure-webpack-plugin')
const Happypack = require('happypack');
const smp = new SpeedMeasureWebpackPlugin()

const webpackConfig = {
    entry: {
        index: './src/index.js',
        login: './src/login.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].[hash:6].js'
    },
    mode: isDev ? 'development' : 'production',
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                use: [
                    // {
                    //     loader: 'cache-loader'
                    // },
                    {
                        loader: 'babel-loader',
                        options: {
                            presets: ["@babel/preset-env"],
                            plugins: [
                                [
                                    "@babel/plugin-transform-runtime",
                                    {
                                        "corejs": 3
                                    }
                                ]
                            ],
                            cacheDirectory: true
                        }
                    },
                ],
                // exclude: /node_modules/
                include: [path.resolve(__dirname, 'src')]
            },
            {
                test: /\.(le|c)ss$/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader, //替换之前的 style-loader, 
                        options: {
                            // hmr: isDev,
                            // reloadAll: true
                        }
                    },
                    'css-loader', 
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: function () {
                                return [
                                    require('autoprefixer')({
                                        "overrideBrowserslist": [
                                            ">0.25%",
                                            "not dead"
                                        ]
                                    })
                                ]
                            }
                        }
                    }, 
                'less-loader'],
                exclude: /node_modules/
            },
            {
                test: /\.(png|jpg|gif|jpeg|webp|svg|eot|ttf|woff|woff2)$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 10240, //即资源大小小于 10K 时，将资源转换为 base64
                            esModule: false,
                            name: '[name]_[hash:6].[ext]',
                            outputPath: 'assets'
                        }
                    }
                ],
                exclude: /node_modules/
            },
            // {
            //     test: /.html$/,
            //     use: 'html-withimg-loader'
            // }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './public/index.html', 
            filename: 'index.html', // 打包后的文件名
            chunks: ['index'],
            minify: {
                removeAttributeQuotes: false, // 是否删除属性的双引号
                collapseWhitespace: false // 是否折叠空白
            },
            // hash: true, // 是否加上hash，默认时false
            config: config.template // 根据不同的环境动态获取到了template
        }),
        new HtmlWebpackPlugin({
            template: './public/login.html',
            filename: 'login.[hash:6].html', //打包后的文件名 且带hash
            chunks: ['login'],  
            config: config.template // 根据不同的环境动态获取到了template
        }),
        new MiniCssExtractPlugin({
            filename: 'css/[name].css'
            //个人习惯将css文件放在单独目录下
            //publicPath:'../'   //如果你的output的publicPath配置的是 './' 这种相对路径，那么如果将css文件放在单独目录下，记得在这里指定一下publicPath 
        }),
        new OptimizeCssPlugin(),
        new CleanWebpackPlugin({
            cleanOnceBeforeBuildPatterns:['**/*', '!dll', '!dll/**'] //不删除dll目录下的文件
        }),
        // ！！！ TODO 这条case没有通过
        // new webpack.DllReferencePlugin({
        //     manifest: path.resolve(__dirname, 'dist', 'dll', 'manifest.json')
        // }),
        new webpack.HotModuleReplacementPlugin() //热更新插件
    ],
    optimization: {
        splitChunks: {//分割代码块
            cacheGroups: {
                vendor: {
                    //第三方依赖
                    priority: 1, //设置优先级，首先抽离第三方模块
                    name: 'vendor',
                    test: /node_modules/,
                    chunks: 'initial',
                    minSize: 0,
                    minChunks: 1 //最少引入了1次
                },
                //缓存组
                common: {
                    //公共模块
                    chunks: 'initial',
                    name: 'common',
                    minSize: 100, //大小超过100个字节
                    minChunks: 3 //最少引入了3次
                }
            }
        },
        runtimeChunk: {
            name: 'manifest'
        }
    },
    devServer: {
        port: '3000', //默认是8080
        quiet: false, //默认不启用
        inline: true, //默认开启 inline 模式，如果设置为false,开启 iframe 模式
        stats: "errors-only", //终端仅打印 error
        overlay: false, //默认不启用
        clientLogLevel: "silent", //日志等级
        compress: true, //是否启用 gzip 压缩
        hot: true,
        before(app){
            apiMocker(app, path.resolve('./mock/mocker.js'))
        },
        contentBase: path.resolve(__dirname, 'dist')
    },
    devtool: 'cheap-module-eval-source-map' //开发环境下使用
}

module.exports = smp.wrap(webpackConfig)